<?php
class Messages_model extends Model {

    function getAllMessages() {
        $messages = $this->db->get('messages');
        $result = $messages->result();
        if ($result > 0) {
            return $result;
        }
        else return false;
    }

    function getAllMessagesByStatus($status){
        $s = $status=="all"?'':'where message_status='.$status;
        $query = $this->db->query("SELECT DISTINCT rm.message_id,m.* FROM rep_messages rm
                                    LEFT JOIN messages m ON m.message_id = rm.message_id ".$s);
        return $query->result();
    }

    function getMessageAnswers($message_id) {
        $this->db->select('*');
        $this->db->from('rep_messages');
        $this->db->join('representatives', 'rep_messages.rep_id = representatives.rep_id','left');
        $this->db->where('rep_messages.message_id', $message_id);
        $query = $this->db->get();
        $result = $query->result();
        if ($result > 0) {
            return $result;
        }
        else return false;
    }

    function insertMessage($data){
        $this->db->insert('messages',$data);
        return $this->db->insert_id();
    }

    function getMessageById($message_id){
        $this->db->select('*');
        $this->db->from('messages');
        $this->db->where('messages.message_id', $message_id);
        $query = $this->db->get();
        return $query->result();
    }

    function deleteMessage($message_id){
        $this->db->where('message_id', $message_id);
        $this->db->delete('messages');
    }

    function checkRepresentativeAccess($rep_id,$message_id,$token){
        $query = $this->db->query("SELECT * FROM messages m
                                    LEFT JOIN rep_messages rm ON m.message_id = rm.message_id
                                    WHERE m.message_id = ".$message_id." AND rm.rep_id=".$rep_id."
                                    AND message_token = '".$token."'");
        return $query->result();
    }

}
?>
